<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
      :disabled="isView"
    >
      <div class="createPost-main-container">
        <el-row gutter="80">
          <el-col :span="12">
            <div class="postInfo-container">
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="roleName"
                  label-width="180px"
                  label="角色名称："
                >
                  <el-input
                    v-model="postForm.roleName"
                    :maxlength="100"
                    name="name"
                    required
                    placeholder="请输入角色名称"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  label-width="180px"
                  label="角色说明："
                >
                  <el-input
                    v-model="postForm.roleDescription"
                    type="textarea"
                    class=""
                    :autosize="{ minRows: 4, maxRows: 8 }"
                    placeholder="请输入角色说明"
                  />
                </el-form-item>
              </el-row>
            </div>
          </el-col>

          <el-col :span="12">
            <el-row>
              <el-form-item
                label-width="100px"
                label="权限列表:"
                prop="rolePermissions"
              >
                <el-select
                  v-model="postForm.rolePermissions"
                  multiple
                  placeholder="请选择权限"
                  :loading="loading"
                >
                  <el-option
                    v-for="item in permissionListOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
      </div>

      <el-button
        v-show="!isView"
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="submitForm"
      >
        保存
      </el-button>
    </el-form>
  </div>
</template>

<script>
import { fetchRoleById, createRole, updateRole } from "@/api/role";
import { fetchAllPermissions } from "@/api/permission";

const defaultForm = {
  roleName: "", // 角色名称
  roleDescription: "", // 角色说明
  rolePermissions: "", // 角色权限列表
  id: undefined,
};

export default {
  name: "RoleDetail",
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (
        (rule.field === "rolePermissions" && value.length === 0) ||
        value === ""
      ) {
        callback(new Error("此为必填项"));
      } else {
        callback();
      }
    };

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      permissionList: [],
      permissionListOptions: [],
      rules: {
        roleName: [{ required: true, validator: validateRequire }],
        rolePermissions: [{ required: true, validator: validateRequire }],
      },
    };
  },
  // computed: {
  //   displayPermissions: {
  //     get() {
  //       return typeof this.postForm.rolePermissions === "object"
  //         ? this.postForm.rolePermissions
  //         : this.postForm.rolePermissions
  //         ? JSON.parse(this.postForm.rolePermissions)
  //         : [];
  //     },
  //     set(val) {
  //       this.postForm.rolePermissions = val;
  //     },
  //   },
  // },
  created() {
    this.getPermissions();
    if (this.isEdit || this.isView) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }
  },
  methods: {
    getPermissions() {
      this.listLoading = true;
      fetchAllPermissions().then((res) => {
        this.permissionList = res.data.map((item) => {
          return {
            label: item.permissionName,
            value: item.id
          };
        });
        this.permissionListOptions = this.permissionList;

        this.listLoading = false;
      });
    },
    getPermissionList(query) {
      if (query !== "") {
        this.loading = true;
        this.permissionListOptions = permissionList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.permissionListOptions = permissionList;
      }
    },
    fetchData(id) {
      fetchRoleById(id)
        .then((res) => {
          this.postForm = res.data[0];
          this.postForm.rolePermissions =
            this.postForm.rolePermissions?.length > 0
              ? JSON.parse(this.postForm.rolePermissions)
              : [];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submitForm() {
      console.log(this.postForm);
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.postForm.id) {
            updateRole(this.postForm.id, this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/role/list");
                  this.$message({
                    title: "成功",
                    message: "角色更新成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "角色更新失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            createRole(this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/role/list");

                  this.$message({
                    title: "成功",
                    message: "角色创建成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "角色创建失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          console.log("角色保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
